package com.example.office.docx2html;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebView;

import org.apache.poi.xwpf.converter.core.IImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


public class MainActivity2 extends Activity {
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);

        // setting
        final String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "_test";
        final String docFile = dir + "/test.docx";
        final String imgFolder = dir + "/html/images/ooxml/";
        final String htmlFile = dir + "/html/test_docx.html";

        try {
            long start = System.currentTimeMillis();
            // 1) Load docx with POI XWPFDocument
            FileInputStream is = new FileInputStream(new File(docFile));
            XWPFDocument document = new XWPFDocument(is);

            // 2) Convert POI XWPFDocument 2 PDF with iText
            File outFile = new File(htmlFile);
            outFile.getParentFile().mkdirs();
            XHTMLOptions options = XHTMLOptions.getDefault();
            options.setExtractor(new IImageExtractor() {
                @Override
                public void extract(String s, byte[] content) throws IOException {
                    OutputStream out = new FileOutputStream(dir + "/" + s);
                    out.write(content, 0, content.length);
                }
            });

            OutputStream out = new FileOutputStream(outFile);
            XHTMLConverter.getInstance().convert(document, out, options);
            System.err.println("Generate html/ooxml.html with " + (System.currentTimeMillis() - start) + "ms");

        } catch(Throwable e) {
            e.printStackTrace();
        }
        // load in webview
        webView.loadUrl("file:///" + htmlFile);
    }
}
